package com.sanrenzu.everybodytv.db;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by asus on 2016/9/9.
 */
public class UserDao {
    //初始化工具类
    private ORMliteHelper orMliteHelper;
    //声明Dao
    private static Dao<Collecion,Integer> dao;
    private static UserDao mDao;

    //创建一个表
    private UserDao(Context context){
        this.orMliteHelper = new ORMliteHelper(context);
        try {
            dao = orMliteHelper.getDao(Collecion.class);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //声明一个单例创建数据库
    private static UserDao userDaoInstence(Context context){
        if (mDao == null) {
            mDao = new UserDao(context);
        }
        return mDao;
    }
    //增加的方法
    //增加的方法
    public static void add(Collecion collecion, Context context){
        userDaoInstence(context);
        try {
            int state = dao.create(collecion);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //删除的方法
    public static void del(Context context,String name ) {
        userDaoInstence(context);
        try {
            ///删除的方法
            DeleteBuilder builder = dao.deleteBuilder();
            //查询的方法
            builder.where().eq("name",name);
            builder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //改的方法
    public static void update(Context context,String name) {
        userDaoInstence(context);
        try {
            UpdateBuilder<Collecion, Integer> builder = dao.updateBuilder();
            builder.where().eq("name",name);
            builder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //查询全部的方法
    public static List<Collecion> quareAll(Context context){
        List<Collecion> list = new ArrayList<>();
        userDaoInstence(context);
        try {
            list= dao.queryForAll();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //查询 单个的方法
    public static List<Collecion> quareOne(Context context,String name){
        List<Collecion> list = new ArrayList<>();
        userDaoInstence(context);
        try {
            QueryBuilder<Collecion, Integer> builder = dao.queryBuilder();
            builder.where().eq("name", name);
            list = builder.query();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}
